<?php

namespace Common\Model;

use Think\Model;

class GoodsModel extends Model {

    protected $_validate = array(/* array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]) */
        array('goodsName', 'require', '请输入商品名称！'),
        array('goodsSn', 'require', '请输入商品编号！'),
        array('catID', 'require', '请指定商品类型！'),
        array('goodsSn', '', '商品编号已经存在！', 0, 'unique', 1),
    );  // 自动验证定义
    protected $_auto = array(/* array(完成字段1,完成规则,[完成条件,附加规则]) */
        array('addTime', 'time', 1, 'function'),
        array('updateTime', 'time', 2, 'function'),
        array('isOn', '1', 1),
    );  // 自动完成定义

    /**
     *  获取单个商品
     */

    public function getGoods($gid = null, $where = array()) {
        if (!empty($gid)) {
            $where['goodsID'] = $gid;
        }

        $result = $this->where($where)->find();

        return $result;
    }

    /**
     * 获得列表（带基本查询）
     */
    public function getGoodsList($pageNo = 1, $pageSize = 15, $where = array(), $order = array()) {
        $rt = $this->where($where)->page("$pageNo,$pageSize")->order($order)->select();
        return $rt;
    }

    public function getGoodsListLength($where = array()) {
        return $this->where($where)->count();
    }

    /**
     * 添加单个信息
     * @return type
     */
    public function addGoods($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->add();
        }
        return $rt;
    }

    /**
     * 更新信息(注意$data一定要有主键id,若$data为空，则默认是对$_POST数组处理)
     * @return type
     */
    public function updateGoods($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->save();
        }
        return $rt;
    }

    /**
     * 删除
     */
    public function deleteGoods($id) {
        if ($id <= 0) {
            $this->error = "无效ID";
            return false;
        }
        $data = array("isOn" => 0, "updateTime" => time());
        return $this->where("goodsID=$id")->save($data);
    }

    /**
     * 判断是否还有该分类商品
     * @param type $catID
     */
    public function isExistByCatID($catID) {
        return $this->where(array("catID" => $catID))->count() > 0;
    }

}
